package com.wmh.baseservice.common.utils.returnbody;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 返回数据实体
 *
 * @author
 */
@Component
public class ReturnBody {


    public static String message(Message message, ResultCodeInfo codeInfo) {
        ResultInfo resultInfo = new ResultInfo(message.getValue(), codeInfo.getCode(), codeInfo.getResult());
        JSONObject jsonObject = JSONObject.parseObject(toJsonString(resultInfo));
        return jsonObject.toString();
    }

    public static String message(Message message, Code code, Object result,JSONWriter.Feature... features) {
        ResultInfo resultInfo = new ResultInfo(message.getValue(), code.getValue(), result);
        JSONObject jsonObject = JSONObject.parseObject(toJsonString(resultInfo,features));
        return jsonObject.toString();
    }


    public static String message(Message message, Integer code, Object result) {
        ResultInfo resultInfo = new ResultInfo(message.getValue(), code, result);
        JSONObject jsonObject = JSONObject.parseObject(toJsonString(resultInfo));
        return jsonObject.toString();
    }


    public static String success() {
        return message(Message.SUCCESS, ResultCodeInfo.SUCCESS);
    }

    public static String success(Object result,JSONWriter.Feature... features) {
        return message(Message.SUCCESS, Code.SUCCESS, result,features);
    }

    public static String success(Code code, Object result) {
        return message(Message.SUCCESS, code, result);
    }


    public static String error() {
        return message(Message.ERROR, ResultCodeInfo.ERROR);
    }
    public static String error(ResultCodeInfo resultCodeInfo) {
        return message(Message.ERROR, resultCodeInfo);
    }

    public static String error(Object result) {
        return message(Message.ERROR, Code.ERROR, result);
    }


    public static String error(Code code, Object result) {
        return message(Message.ERROR, code, result);
    }

    public static String error(Integer code, Object result) {
        return message(Message.ERROR, code, result);
    }


    /**
     * 解决序列化 超 17 位 的 Long 置于 前端时丢失精度问题
     * */
    private static String toJsonString(Object info,JSONWriter.Feature... features){
        List<JSONWriter.Feature> featureList = Arrays.stream(features).collect(Collectors.toList());
        featureList.add(JSONWriter.Feature.BrowserCompatible);
        return JSONObject.toJSONString(info, featureList.toArray(new JSONWriter.Feature[0]));
    }

    /**
     *
     * */
    private static String toJsonString(Object info, boolean isIgnoreNull){
        if (isIgnoreNull){
            return toJsonString(info);
        }else{
            return JSONObject.toJSONString(info,JSONWriter.Feature.BrowserCompatible,JSONWriter.Feature.NullAsDefaultValue);
        }
    }
}
